<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Rank;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class RankController extends Controller
{
    public function all(Request $request)
    {
        $items = Rank::all();
        return jsonResponse(config('common.successCode'), $items);
    }

    public function create(Request $request)
    {
        $validator = $this->validate($request);
        if ($validator->fails()) {
            return jsonResponse(config('common.validatorError'), $validator);
        }

        $title = $request->get('title');
        $min = $request->get('min');
        $max = $request->get('max');

        $items = Rank::where('min_point', '>=', $max)->get();
        foreach ($items as $item) {
            if ($item['max'] > $min) {
                return jsonResponse(41600);
            }
        }

        $rank = new Rank();
        $rank['title'] = $title;
        $rank['min_point'] = $min;
        $rank['max_point'] = $max;
        $rank['discount'] = 100;
        $rank['show_price'] = 0;
        $rank['if_special'] = 0;
        $rank->save();
        return jsonResponse();
    }

    public function update(Request $request, $id)
    {
        $validator = $this->validate($request);
        if ($validator->fails()) {
            return jsonResponse(config('common.validatorError'), $validator);
        }
        $title = $request->get('title');
        $min = $request->get('min');
        $max = $request->get('max');

        $items = Rank::where('min_point', '>=', $max)->get();
        foreach ($items as $item) {
            if ($item['max'] > $min) {
                return jsonResponse(41600);
            }
        }

        $rank = Rank::find($id);
        if (empty($rank)) {
            return jsonResponse(40000);
        }
        $rank['title'] = $title;
        $rank['min_point'] = $min;
        $rank['max_point'] = $max;
        $rank->save();
        return jsonResponse();
    }

    public function destroy(Request $request, $id)
    {
        Rank::destroy($id);
        return jsonResponse();
    }

    private function validate($request)
    {
        return Validator::make($request->all(), [
            'title' => 'required',
            'min_point' => 'required|integer',
            'max_point' => 'required|integer|gt:min_point',
        ], [
            'title.required' => '名称不能为空',
            'min_point.required' => '最小积分不能为空',
            'min_point.integer' => '最小积分必须为数字',
            'max_point.required' => '最大积分不能为空',
            'max_point.integer' => '最大积分必须为数字',
            'max_point.gt' => '最大积分必须大于最小积分',
        ]);
    }
}
